<template>
	<view class="page">
		<!-- 公共组件-每个页面必须引入 -->
		<public-module></public-module>
		<view class="f-register pb-save-140">
			<view class="title">身份认证</view>
			<view class="desc">完善下列资料并通过认证，就可以接单啦~</view>
			<view class="steps-box">
				<u-steps :current="currentStep" :activeColor="PrimaryColor">
					<u-steps-item title="基本信息" class="active-step"></u-steps-item>
					<u-steps-item title="资质证书"></u-steps-item>
				</u-steps>
			</view>

			<view class="loginPhone">
				<u--form labelPosition="left" labelWidth="160rpx" :model="formData" :rules="rules" ref="uForm">
					<view v-if="currentStep==0">
						<view class="idcard-box">
							<u-form-item label="身份证" prop="workDate" labelPosition="top">
								<view class="u-flex u-flex-items-center u-flex-between u-m-t-10">
									<u-upload :fileList="fileListIdImageFront" @afterRead="afterRead"
										@delete="deletePic" name="IdImageFront" multiple :maxCount="1" width="314rpx"
										height="206rpx">
										<view class="upload-idcard">
											<image src="/staticn-idfront.png"></image>
										</view>
									</u-upload>
									<u-upload :fileList="fileListIdImageBack" @afterRead="afterRead" @delete="deletePic"
										name="IdImageBack" multiple :maxCount="1" width="314rpx" height="206rpx">
										<view class="upload-idcard">
											<image src="/staticn-idback.png"></image>
										</view>
									</u-upload>
								</view>
							</u-form-item>
							<u-form-item label="证件有效期" prop="name">
								<u--input border="none" class="input" type="text" v-model="idcardLimitTime"
									inputAlign="right"></u--input>
							</u-form-item>
						</view>
						<view class="line-title">填写基本信息</view>
						<u-form-item label="头像" prop="avatar" borderBottom>
							<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
								<image class="avatar" :src="avatarUrl || '/pages-single/static/head.png'"></image>
							</button>
						</u-form-item>
						<u-form-item label="姓名" prop="name" borderBottom>
							<u--input border="none" class="input" type="text" v-model="formData.name" clearable
								placeholder="请输入姓名"></u--input>
						</u-form-item>
						<u-form-item label="身高" prop="height" borderBottom>
							<u--input border="none" class="input" type="number" v-model="formData.height" clearable
								placeholder="请输入身高"></u--input>
							<text slot="right">CM</text>
						</u-form-item>
						<u-form-item label="体重" prop="weight" borderBottom>
							<u--input border="none" class="input" type="number" v-model="formData.weight" clearable
								placeholder="请输入体重"></u--input>
							<text slot="right">KG</text>
						</u-form-item>
						<u-form-item label="婚姻" prop="maritalStatus" borderBottom @click="showMaritalAction = true;">
							<u--input border="none" class="input" disabled disabledColor="#ffffff"
								v-model="formData.maritalStatus" placeholder="请选择婚姻"></u--input>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
						<!-- <u-form-item label="户籍" prop="hometown" borderBottom>
							<u--input border="none" class="input" type="text" v-model="formData.hometown"
								placeholder="请选择户籍"></u--input>
						</u-form-item> -->
						<view class="line-title">填写技能信息</view>
						<u-form-item label="从业时间" prop="workTime" borderBottom @click="showWorkTime = true;">
							<u--input border="none" class="input" type="text" v-model="formData.workTime"
								placeholder="请选择从业时间"></u--input>
						</u-form-item>
						<u-form-item label="技能" labelPosition="top" prop="phone" borderBottom
							@click="showSkill = true;">
							<view class="selected-label u-flex u-flex-wrap" v-if="skillLabels.length>0">
								<view class="label-tag" v-for="(item,index) in skillLabels" :key="index">{{item.name}}
								</view>
							</view>
							<view v-else>请选择技能</view>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
					</view>
					<view v-if="currentStep==1">
						<view class="line-title">上传证件资质</view>
						<view class="idcard-box">
							<u-form-item label="健康证" prop="workDate" labelPosition="top">
								<view class="u-flex u-flex-items-center u-flex-between u-m-t-10">
									<u-upload :fileList="fileListHeather" @afterRead="afterRead" @delete="deletePic"
										name="Heather" multiple :maxCount="1" width="314rpx" height="206rpx">
										<view class="upload-camare">
											<image src="/pages-single/static/icon-camare.png"></image>
										</view>
									</u-upload>
									<image src="/pages-single/static/img-heather.png" mode="widthFix"
										style="width: 314rpx; ">
									</image>
								</view>
							</u-form-item>
							<u-form-item label="有效期">
								<uni-datetime-picker v-model="heatherDate" type="daterange" start="2020-1-1"
									end="2099-12-31" :border="false" rangeSeparator="至" />
							</u-form-item>
						</view>
						<view class="idcard-box u-m-t-20">
							<u-form-item label="从业资格证" prop="workDate" labelPosition="top">
								<view class="u-flex u-flex-items-center u-flex-between u-m-t-10">
									<u-upload :fileList="fileListCareworkerCert" @afterRead="afterRead"
										@delete="deletePic" name="CareworkerCert" multiple :maxCount="1" width="314rpx"
										height="206rpx">
										<view class="upload-camare">
											<image src="/pages-single/static/icon-camare.png"></image>
										</view>
									</u-upload>
									<image src="/pages-single/static/img-cert.png" mode="widthFix"
										style="width: 314rpx; ">
									</image>
								</view>
							</u-form-item>

							<u-form-item label="有效期">
								<uni-datetime-picker v-model="careworkerCertDate" type="daterange" start="2020-1-1"
									end="2099-12-31" :border="false" rangeSeparator="至" />
							</u-form-item>
						</view>

						<view class="idcard-box u-m-t-20">
							<u-form-item label="其他证书" prop="workDate" labelPosition="top">
								<view class="u-flex u-flex-items-center u-flex-between u-m-t-10">
									<u-upload :fileList="fileListOtherCert" @afterRead="afterRead" @delete="deletePic"
										name="OtherCert" :maxCount="9">
									</u-upload>
								</view>
							</u-form-item>

						</view>
					</view>
				</u--form>
			</view>
		</view>
		<view class="save-bottom">
			<view class="fix-btn" v-if="currentStep==0">
				<u-button type="primary" class="btn" shape="circle" text="下一步" @click="onNext" size="large"></u-button>
			</view>
			<view class="fix-btn u-flex" v-if="currentStep==1">
				<u-button type="primary" :hairline="true" :plain="true" text="上一步" shape="circle" @click="onPrev"
					size="large"></u-button>
				<u-button type="primary" class="btn" shape="circle" text="提交" @click="onSubmit" size="large"></u-button>
			</view>
		</view>
		<u-action-sheet safeAreaInsetBottom :show="showMaritalAction" :actions="maritalOptions" title="请选择婚姻"
			@close="showMaritalAction = false" @select="maritalStatusSelect">
		</u-action-sheet>
		<u-datetime-picker :show="showWorkTime" v-model="workTime" @cancel="showWorkTime = false"
			@confirm="workTimeSelect" mode="date"></u-datetime-picker>
		<u-popup :show="showSkill" mode="bottom" @open="openSkill">
			<view class="popup-title">
				<text>请选择技能标签</text>
			</view>
			<view class="skill-list-box u-flex u-flex-wrap">
				<view class="skill-label" v-for="(item, index) in skillList" :key="index">
					<u-tag :text="item.name" :plain="!item.checked" type="primary" :name="index"
						@click="checkboxSkillClick" size="large">
					</u-tag>
				</view>
			</view>
			<view class="popup-fixed">
				<u-button type="primary" class="btn" text="确定" @click="onSubmitSkill" size="large"></u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	var clear;
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import {
		completedRegister,
		getDicts,
		getIdcardInfo,
		getUserInfo
	} from '@/config/api';
	import uploadFile from '@/common/ossutil/uploadFile.js'


	export default {
		data() {
			return {
				currentStep: 0,
				readonly: false,
				fileListIdImageFront: [],
				fileListIdImageBack: [],
				showMaritalAction: false,
				maritalOptions: [],
				showSkill: false,
				skillList: [],
				skillLabels: [],
				showWorkTime: false,
				rules: {
					name: [{
						required: true,
						message: '请输入姓名',
						trigger: ['blur'],
					}]
				},
				formData: {
					name: ""
				},
				idcardLimitTime: "",
				fileListHeather: [],
				heatherDate: [],
				fileListCareworkerCert: [],
				careworkerCertDate: [],
				fileListOtherCert: [],
			};
		},
		computed: {
			...mapState(['PrimaryColor', 'userInfo'])
		},
		//第一次加载
		onLoad(e) {
			this.getMaritalStatus()
			this.getCareworkerSkill()
			this.formData = this.userInfo.userInfo
			this.workTime = this.formData.workTime
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		//页面显示
		onShow() {},
		//方法
		methods: {
			...mapMutations(['setUserInfo']),
			getMaritalStatus() {
				getDicts("sys_marital_status").then((res) => {
					console.log(res)
					this.maritalOptions = res.map(item => {
						let tempItem = {
							name: item.dictLabel,
							value: item.dictValue
						}
						return tempItem;
					})
				}).catch((err) => {
					console.log(err, 'catch')
				})
			},
			getCareworkerSkill() {
				getDicts("careworker_skill").then((res) => {
					let tempSkillLabels = this.skillLabels.map(item => {
						return item.skillType
					})
					this.skillList = res.map(item => {
						let tempItem = {
							name: item.dictLabel,
							skillType: item.dictValue,
							checked: false
						}
						if (tempSkillLabels.includes(tempItem.skillType)) {
							tempItem.checked = true
						}
						return tempItem;
					})
				}).catch((err) => {
					console.log(err, 'catch')
				})
			},
			maritalStatusSelect(e) {
				this.formData.maritalStatus = e.name
				this.$refs.uForm.validateField('maritalStatus')
				this.showMaritalAction = false
			},
			workTimeSelect(e) {
				this.formData.workTime = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
				this.showWorkTime = false
			},
			onJump(url) {
				uni.navigateTo({
					url: url
				})
			},
			openSkill() {
				// console.log('open');
			},
			checkboxSkillClick(name) {
				this.skillList[name].checked = !this.skillList[name].checked
			},
			onSubmitSkill() {
				this.skillLabels = this.skillList.filter(item => {
					return item.checked
				});
				this.showSkill = false
			},
			onNext() {
				this.currentStep = 1
			},
			onPrev() {
				this.currentStep = 0
			},
			// 提交完善资料信息
			onSubmit() {
				this.$refs.uForm.validate().then(res => {
					let certList = []
					// 加入健康证信息
					if (this.fileListHeather.length > 0) {
						let tempItem = {
							certType: "",
							effectStartDate: "",
							effectEndDate: "",
							fileList: [],
						}
						tempItem.certType = "heather"
						tempItem.effectStartDate = this.heatherDate[0]
						tempItem.effectEndDate = this.heatherDate[1]
						tempItem.fileList.push({
							fileClassify: "heather",
							fileUrl: this.fileListHeather[0].url
						})
						certList.push(tempItem)
					}
					// 加入陪护从业资格证信息
					if (this.fileListCareworkerCert.length > 0) {
						let tempItem = {
							certType: "",
							effectStartDate: "",
							effectEndDate: "",
							fileList: [],
						}
						tempItem.certType = "careworkerCert"
						tempItem.effectStartDate = this.careworkerCertDate[0]
						tempItem.effectEndDate = this.careworkerCertDate[1]
						tempItem.fileList.push({
							fileClassify: "careworkerCert",
							fileUrl: this.fileListCareworkerCert[0].url
						})
						certList.push(tempItem)
					}
					// 加入其他证件信息
					if (this.fileListOtherCert.length > 0) {
						let tempItem = {
							certType: "",
							effectStartDate: "",
							effectEndDate: "",
							fileList: [],
						}
						tempItem.certType = "OtherCert"
						for (var i = 0; i < this.fileListOtherCert.length; i++) {
							tempItem.fileList.push({
								fileClassify: "OtherCert",
								fileUrl: this.fileListOtherCert[i].url
							})
						}
						certList.push(tempItem)
					}
					let params = {
						...this.formData,
						...{
							skillList: this.skillLabels,
							certList: certList
						}
					}
					completedRegister(params).then((res) => {
						getUserInfo().then((ress) => {
							this.userInfo.userInfo = ress
							// 储存登录信息 
							this.setUserInfo(this.userInfo)
							uni.showToast({
								title: '提交成功~',
								icon: 'none'
							});
							setTimeout(() => {
								uni.switchTab({
									url: '/pages-single/order/order'
								})
							}, 500)
						})
					})
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length - 1
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					uploadFile(lists[i].url, 'xyh_manger_file/', res => {
						let item = this[`fileList${event.name}`][fileListLen];
						this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: res
						}))
						if (event.name === 'IdImageFront') {
							let params = {
								idcardUrl: res,
								isFront: 1
							}
							this.formData.idNumberHeadUrl = res;
							getIdcardInfo(params).then((ress) => {
								console.log(ress)
								if (ress.success) {
									this.formData.name = ress.name
									this.formData.idNumber = ress.idNumber
									this.formData.birth = this.formatStringData(ress.birth)
									this.formData.sex = ress.gender === "男" ? 1 : ress.gender === "女" ?
										0 : 2
									this.formData.nation = ress.nation

								} else {
									uni.showToast({
										title: ress.errorMessage,
										icon: none
									})
								}
								// address: "江苏省海安市银杏村十二组62号"

							})
						} else if (event.name === 'IdImageBack') {
							let params = {
								idcardUrl: res,
								isFront: 0
							}
							this.formData.idNumberBadgeUrl = res;
							getIdcardInfo(params).then((ress) => {
								console.log(ress)
								if (ress.success) {
									this.formData.idNumberStartDate = this.formatStringData(ress
										.startDate)
									if (ress.endDate === "长期") {
										this.formData.idNumberEndDate = ""
										this.formData.idNumberLongValidity = 1
									} else {
										this.formData.idNumberEndDate = this.formatStringData(ress
											.endDate)
									}

									this.idcardLimitTime = ress.startDate + "~" + ress.endDate
									this.formData.issuingAuthority = ress.publishAddress
								} else {
									uni.showToast({
										title: ress.errorMessage,
										icon: none
									})
								}
							})
						}
					})
					fileListLen++
				}
			},
			formatStringData(val) {
				return val.slice(0, 4) + '-' + val.slice(4, 6) + '-' + val.slice(6, 8)
			}
		}
	};
</script>
<style lang="scss" scoped>
	.page {
		min-height: 100vh;
		background-color: #fff;

		.fix-btn {
			z-index: 98;
		}
	}

	.f-register {
		padding: 40rpx 30rpx;
		z-index: 99;
		position: relative;

		.title {
			font-weight: 500;
			color: #303030;
			font-size: 42rpx;
		}

		.desc {
			font-size: 28rpx;
			color: #666;
		}
	}

	.line-title {
		font-size: 32rpx;
		font-weight: 500;
		color: #2B2B31;
		line-height: 45rpx;
		padding: 30rpx 0;
		border-bottom: 1px solid #EEEEEE;
	}

	.loginPhone {
		margin-top: 20rpx;

		.avatar-wrapper {
			width: 70rpx;
			height: 70rpx;
			border-radius: 10rpx;

			.avatar {
				width: 70rpx;
				height: 70rpx;
				border-radius: 10rpx;
			}
		}

		.idcard-box {
			border: 2rpx dashed #EEEEEE;
			padding: 0 20rpx;
			width: 100%;
			box-sizing: border-box;

			.upload-idcard {
				display: flex;
				align-items: center;
				justify-content: center;
				background: #F7F8F9;
				border-radius: 12rpx;
				width: 314rpx;
				height: 206rpx;

				image {
					width: 211rpx;
					height: 153rpx;
				}
			}

			.upload-camare {
				display: flex;
				align-items: center;
				justify-content: center;
				background: #F7F8F9;
				border-radius: 12rpx;
				width: 314rpx;
				height: 206rpx;

				image {
					width: 78rpx;
					height: 78rpx;
				}
			}

			:v-deep .u-upload :last-child {
				margin-left: 20rpx;
			}
		}

		.input {
			width: 100%;
			box-sizing: border-box;
			font-size: 30rpx;
			padding: 0;
		}

		.selected-label {
			padding: 0;
			display: flex;

			.label-tag {
				display: block;
				margin-right: 10rpx;
				margin-top: 10rpx;
				padding: 8rpx 12rpx;
				background: rgba(29, 213, 187, 0.1);
				border-radius: 6rpx;
				font-size: 24rpx;
				font-weight: 500;
				color: #1DD5BB;
			}
		}
	}

	.steps-box {
		margin-top: 40rpx;

		::v-deep .active-step {

			.u-text__value--main {
				color: $uni-color-primary;
			}
		}
	}

	.popup-title {
		padding: 30rpx;

		text {
			font-weight: 500;
		}
	}

	.skill-list-box {
		padding: 0 0 30rpx 30rpx;

		.skill-label {
			margin-right: 20rpx;
			margin-top: 20rpx;
		}
	}

	.popup-fixed {
		padding: 0 30rpx;
	}
</style>
